<template>
    <div>
        <goback :getName='goName' :getURL ="goType" :getBtn='goBtn'></goback>
        <div class="addAddress" @click="showPopup">添加新地址</div>
        <div class="myAddress" v-if="isOwnAddress" v-for="(info,index) of myInfo" :key="index" v-show="isShowAddress">
            <div class="address-info" @click="selectAddress(info)">
                <span class="my-name">{{info.name}}</span>
                <span class="my-blank"></span>
                <span class="my-tel">{{info.phone}}</span>
                <div class="my-address">{{info.address}}</div>
            </div>
            <div class="myAddress-bottom">
                <mt-checklist v-model="value" :options="info.options" @change="defaultAddress(info)"></mt-checklist>
                <div class="delete-address" @click="delSelectedAddress(info.id)">删除</div>
            </div>
        </div>
        <transition name="addNewAddress">
            <div class="addNewAddress" v-if="isShowAddAddress">
                <div class="top">
                    <div class="comeback_">
                        <div @click="hidePopup">
                            <img src="../../assets/other/goback.png" alt="">
                        </div>
                    </div>
                    <span>添加收货地址</span>
                </div>
                <div class="detail-informations">
                    <div>
                        <span>收货人</span>
                        <input type="text" v-model="detailInfo.name" placeholder="请输入姓名">
                    </div>
                    <div>
                        <span>联系电话</span>
                        <input type="text" v-model="detailInfo.tel" placeholder="请输入联系电话">
                    </div>
                    <div>
                        <span>所在地区</span>
                        <div class="address">
                            <input type="text" v-model="completeAddress" maxlength="80" readonly="readonly" @click="showAddressPicker"
                            />
                            <mt-popup v-model="address.regionVisible" position="bottom" class="region-popup">
                                <mt-picker :slots="address.myAddressSlots" valueKey="name" :visibleItemCount="5" @change="addressChange" :itemHeight="40"></mt-picker>
                            </mt-popup>
                        </div>
                        <div class="arrowLogo">
                            <img src="../../assets/other/goback.png" alt="">
                        </div>
                    </div>
                    <div class="detail-address">
                        <span>详细地址</span>
                        <input type="text" v-model="detailInfo.address" placeholder="请输入街道小区详细地址 ">
                    </div>
                </div>
                <div class="set-default-address">
                    <div>
                        <span>设为默认地址</span>
                        <mt-switch v-model="detailInfo.switchButton"></mt-switch>
                    </div>
                </div>
                <mt-button type="danger" @click="addNewAddress">保存</mt-button>
            </div>
        </transition>
    </div>
</template>
<script>
    import { Checklist, MessageBox, Picker, Indicator } from 'mint-ui'
    import goback from '../../components/goback'
    import { userInfoGet } from '../../libs/publicMethod'  // 获取用户信息
    import { getAddressList, addAddress, delAddress, setDefaultAddress } from '../../libs/interface' // 获取接口
    //引入省市区数据json文件
    import threeLevelAddress from '../../libs/pca-code.json'
    export default {
        components: { goback, getAddressList, addAddress, delAddress, setDefaultAddress, Checklist, MessageBox, Picker, Indicator },
        data () {
            return {
                goName: '收货地址',
                goType: '', // 导航返回页面，如返回上一级则为空
                goBtn: '', // 导航右边菜单，如没有则不填
                userInfo: userInfoGet(), // 用户信息
                isOwnAddress: true, // 是否显示我的地址
                value: [],
                isShowAddAddress: false, // 添加新地址
                isShowAddress: true,
                completeAddress: '', // 完整地址
                address: {
                    region: '',//三级地址
                    province: '',//省
                    city: '',//市
                    county: '',//县
                    provinceCode: '',//省级代码
                    cityCode: '', //市级代码
                    countyCode: '', //县级代码
                    regionVisible: false, //弹出框是否可见
                    regionInit: false, //禁止地区选择器自动初始化，picker组件会默认进行初始化，导致一进入页面就会默认选中一个初始3级地址
                    //picker组件插槽
                    myAddressSlots: [
                        //省
                        {
                            flex: 1,
                            values: this.getProvinceArr(), //省份数组
                            className: 'slot1',
                            textAlign: 'center'
                        },
                        {
                            divider: true,
                            content: '',
                            className: 'slot2'
                        },
                        //市
                        {
                            flex: 1,
                            values: this.getCityArr("北京市"),
                            className: 'slot3',
                            textAlign: 'center'
                        },
                        {
                            divider: true,
                            content: '',
                            className: 'slot4'
                        },
                        //县
                        {
                            flex: 1,
                            values: this.getCountyArr("北京市", "市辖区"),
                            className: 'slot5',
                            textAlign: 'center'
                        }
                    ],
                },
                detailInfo: {
                    name: '',
                    phone: '',
                    address: '',
                    switchButton: false, // 设为默认地址
                },
                myInfo: [],
            }
        },
        methods: {
            // 删除地址
            delSelectedAddress (id) {
                let vm = this
                MessageBox.confirm('', {
                    title: '确定删除',
                    message: '是否删除这个收货地址',
                }).then( () => {
                    vm.myInfo.forEach(function (elem, index) {
                        if (elem.id === id) {
                            let params = {
                                memberid: vm.userInfo.id + 0,
                                addressid: elem.id,
                            }
                            delAddress(params, (data) => {
                                if (data.code === 1) {
                                    let deleteOne = vm.myInfo.splice(index, 1)
                                    if (deleteOne[0].isdefault === 1) {
                                        if (vm.myInfo.length >= 1) {
                                            vm.myInfo.forEach((e) => {
                                                let param = {
                                                    memberid: vm.userInfo.id + 0,
                                                    addressid: vm.myInfo[vm.myInfo.length - 1].id,
                                                }
                                                setDefaultAddress(param, (data) => {
                                                    if (data.code === 1) {
                                                        vm.myInfo[vm.myInfo.length - 1].isdefault = 1
                                                        vm.value = [vm.myInfo[vm.myInfo.length - 1].id]
                                                    }
                                                })
                                            })
                                        }
                                    }
                                    vm.$toast(data.msg)
                                } else vm.$toast('删除失败')
                            })
                        }
                    })
                })
            },
            // 添加地址
            addNewAddress() {
                let vm = this
                let reg = /^1\d{10}$/
                if (!reg.test(vm.detailInfo.tel)) {
                    vm.$toast('请输入正确的手机号')
                    return
                }
                if (vm.detailInfo.name === '') {
                    vm.$toast('请填写姓名')
                    return
                }
                if (vm.completeAddress === '') {
                    vm.$toast('请填写地址')
                    return
                }
                Indicator.open({
                    text: '保存中...',
                    spinnerType: 'fading-circle'
                })
                let params = {
                    memberid: vm.userInfo.id + 0,
                    name: vm.detailInfo.name,
                    phone: vm.detailInfo.tel,
                    postcode: 666666,
                    address: vm.completeAddress+vm.detailInfo.address,
                    isDefault: vm.detailInfo.switchButton + 0,
                }
                if (vm.myInfo.length == 0) {
                    params.isDefault = 1
                    this.detailInfo.switchButton = true
                }
                addAddress(params, (data) => {
                    if (data.code === 1) {
                        setTimeout(() => {
                            Indicator.close()
                            vm.$toast(data.msg)
                            this.hidePopup()
                            let param = {
                                memberid: vm.userInfo.id,
                            }
                            getAddressList(param, (data) => {
                                vm.myInfo = data.payload
                                for (let elem of vm.myInfo) {
                                    elem.options = [
                                        {
                                            label: '设为默认',
                                            value: elem.id
                                        },
                                    ]
                                    if (elem.isdefault === 1) {
                                        vm.value = [elem.id]
                                    }
                                }
                            })
                        }, 300);
                    } else vm.$toast('添加失败')
                })
            },
            // 设为默认地址
            defaultAddress (info) {
                let vm = this
                if (info.id === vm.value[0]) {
                    return
                }
                let params = {
                    memberid: vm.userInfo.id + 0,
                    addressid: info.id,
                }
                setDefaultAddress(params, (data) => {
                    if (data.code === 1) {
                        vm.myInfo.forEach((elem)=>{
                            if (elem.isdefault) {
                                elem.isdefault = 0
                            }
                        })
                        info.isdefault = 1
                        vm.$toast(data.msg)
                        if (vm.$route.params.isSelected === '1') {
                            sessionStorage.setItem('addressinfoSet', JSON.stringify(info))
                        }
                    } else vm.$toast('设置失败')
                })
            },
            // 选择地址
            selectAddress (info) {
                let vm = this
                if (vm.$route.params.isSelected === '0') return
                // 设置地址
                sessionStorage.setItem('addressinfoSet', JSON.stringify(info))
                history.back()
            },
            // 显示添加新地址
            showPopup () {
                this.isShowAddAddress = true
                setTimeout(() => {
                    this.isShowAddress = false
                }, 300);
                this.detailInfo = {
                    name: '',
                    phone: '',
                    address: '',
                    switchButton: false, // 设为默认地址
                }
            },
            // 隐藏添加新地址
            hidePopup () {
                this.isShowAddAddress = false
                this.isShowAddress = true
            },
            // 打开地址选择器
            showAddressPicker () {
                this.address.regionVisible = true
            },
            //picker组件的change事件，进行取值赋值
            addressChange (picker, values) {
                if (this.address.regionInit) {
                    //取值并赋值
                    // this.address.region = values[0]["name"] + values[1]["name"] + values[2]["name"]
                    this.address.province = values[0]["name"]
                    this.address.city = values[1]["name"]
                    this.address.county = values[2]["name"]
                    this.address.region = this.address.province + this.address.city + this.address.county
                    this.address.provinceCode = values[0]["code"]
                    this.address.cityCode = values[1]["code"]
                    this.address.countyCode = values[2]["code"]
                    //给市、县赋值
                    picker.setSlotValues(1, this.getCityArr(values[0]["name"]))
                    picker.setSlotValues(2, this.getCountyArr(values[0]["name"], values[1]["name"]))
                    if (this.address.region.indexOf('市辖区') != -1) {
                        this.completeAddress = this.address.region.replace('市辖区', '')
                    } else if (this.address.region.indexOf('县') != -1) {
                        this.completeAddress = this.address.region.replace('县', '')
                    } else this.completeAddress = this.address.region
                } else {
                    this.address.regionInit = true
                }
            },
            //遍历json，返回省级对象数组
            getProvinceArr () {
                let provinceArr = []
                threeLevelAddress.forEach(function (item) {
                    let obj = {}
                    obj.name = item.name
                    obj.code = item.code
                    provinceArr.push(obj)
                });
                return provinceArr
            },
            //遍历json，返回市级对象数组
            getCityArr (province) {
                let cityArr = []
                threeLevelAddress.forEach(function (item) {
                    if (item.name === province) {
                        item.children.forEach(function (args) {
                            let obj = {};
                            obj.name = args.name
                            obj.code = args.code
                            cityArr.push(obj)
                        });
                    }
                });
                return cityArr
            },
            //遍历json，返回县级对象数组
            getCountyArr (province, city) {
                let countyArr = []
                threeLevelAddress.forEach(function (item) {
                    if (item.name === province) {
                        item.children.forEach(function (args) {
                            if (args.name === city) {
                                args.children.forEach(function (param) {
                                    let obj = {};
                                    obj.name = param.name
                                    obj.code = param.code
                                    countyArr.push(obj)
                                })
                            }
                        })
                    }
                });
                return countyArr
            },
        },
        mounted () {
            document.body.style.paddingBottom = 0
            let vm = this
            let params = {
                memberid: vm.userInfo.id,
            }
            getAddressList(params, (data) => {
                vm.myInfo = data.payload
                for (let elem of vm.myInfo) {
                    elem.options = [
                        {
                            label: '设为默认',
                            value: elem.id
                        },
                    ]
                    if (elem.isdefault === 1) {
                        vm.value = [elem.id]
                    }
                }
            })
        },
        watch: {
            value () {
                let vm = this
                let arr = []
                if (vm.value.length > 1) {
                    vm.value = vm.value.splice(vm.value.length - 1,1)
                }
            },
        }
    }
</script>
<style>
a{
    color: #333;
}
.addAddress{
    height: 3.6rem;
    line-height: 3.6rem;
    font-size: 1.1rem;
    border: 1.1px solid #D2D2D2;
    border-left-width: 2px;
    border-right-width: 2px;
    margin-top: 18%;
    background-color: #fff;
}
.myAddress{
    height: 7.5rem;
    margin-top: 4%;
    border: 1.1px solid #DCDCDF;
    background-color: #fff;
}
.address-info{
    height: 4.6rem;
    border-bottom: 1px solid #E1E1E3;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-wrap: wrap;
}
.address-info span {
    display: inline-block;
}
.my-name{
    margin-left: 4%;
    text-align: left;
    font-size: 1.05rem;
    width: 30%;
}
.my-blank{
    width: 34%;
    height: 1rem;
}
.my-tel{
    margin-right: 2%;
    width: 30%;
    font-size: 1rem;
}
.my-address{
    width: 92%;
    margin: 0 auto;
    margin-top: -1rem;
    text-align: left;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.mint-checkbox-input:checked + .mint-checkbox-core{
    background-color: #09BB07;
    border-color: #09BB07;
}
.mint-checklist{
    width: 5rem;
    margin-left: 1rem;
}
.mint-checklist .mint-cell{
    min-height: 1.8rem;
}
.mint-checkbox-core{
    width: 15px;
    height: 15px;
}
.mint-checkbox-core::after{
    width: 3px;
    height: 6px;
    top: 2px;
    left: 5px;
}
.mint-cell{
    margin-left: 0rem;
}
.mint-checklist-label{
    padding: 0;
    width: 5rem;
}
.mint-cell-wrapper{
    font-size: .8rem;
    width: 5rem;
    padding: 0;
    background-image: none;
}
.mint-cell:last-child{
    background-size: 100% 0;
}
.myAddress-bottom{
    position: relative;
}
.delete-address{
    position: absolute;
    right: 4%;
    top: 6%;
    border: 1px solid #E1E1E3;
    font-size: .9rem;
    color: #333;
    width: 3rem;
    height: 1.5rem;
    line-height: 1.5rem;
}
.mint-msgbox-message{
    font-size: .9rem;
}
.mint-msgbox-confirm{
    color: #09BB07;
    font-size: 1rem;
}
.mint-msgbox-cancel{
    font-size: 1rem;
}
.addNewAddress-enter-active{
    transform: translateY(0);
    transition: all .3s ease;
}
.addNewAddress-leave-active{
    transform: translateY(100%);
    transition: all .3s ease;
}
.addNewAddress-enter{
    transform: translateY(100%);
}
.addNewAddress-leave{
    transform: translateY(0);
}
.addNewAddress{
    width: 100%;
    height: 100%;
    background-color: #F0F0F0;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 10;
}
.detail-informations{
    margin-top: 15%;
    height: 14.5rem;
    width: 100%;
}
.detail-informations>div{
    width: 100%;
    height: 24.5%;
    border-top: 1px solid #CECED2;
    text-align: left;
    display: flex;
    align-items: center;
    background-color: #fff;
}
.detail-informations span{
    display: inline-block;
    width: 20%;
    padding-left: 4%;
    padding-right: 4%;
}
.detail-informations input{
    outline: none;
    font-size: .95rem;
    border: none;
    caret-color : #4C9AFA;
}
.detail-informations input::placeholder{
    color: #666666;
    font-size: .9rem;
}
.detail-address{
    border-bottom: 1px solid #CECED2;
}
.top{
    height: 2.4rem;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    background-color: #fff;
}
.comeback_>div{
    width: 1.2rem;
    height: 1.2rem;
    position: absolute;
    left: .5rem;
    top: 0;
    bottom: 0;
    margin: auto;
}
.comeback_ img{
    height: 1.2rem;
}
.set-default-address{
    margin-top: 5%;
    width: 100%;
    height: 2.5rem;
    background-color: #fff;
    border-top: 1px solid #CECED2;
    border-bottom: 1px solid #CECED2;
}
.set-default-address>div{
    width: 92%;
    height: 100%;
    margin: 0 auto;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.mint-switch-input:checked + .mint-switch-core{
    background-color: #09BB07;
    border-color: #09BB07;
}
.region-popup{
    width: 100%;
}
.address{
    width: 65%;
}
.arrowLogo{
    width: .7rem;
    height: .7rem;
    transform: rotateY(180deg);
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 0%;
    opacity: .3;
}
.arrowLogo img{
    width: 100%;
    height: 100%;
}
.mint-button--danger{
    margin-top: 6%;
    width: 94%;
    height: 8.5%;
    font-size: .9rem;
    color: #FCEAEA;
}
.mint-indicator{
    position: relative;
    z-index: 100;
}
</style>